package CPM;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class DBIndex {
	public static void main(String args[]) throws Exception {

		Configuration conf=new Configuration();
		String per_entity_index=conf.getPerEntityIndex();
		Connection con = null;
		String url = "jdbc:mysql://localhost:3306/";
		String db = "cpmnew";
		String driver = "com.mysql.jdbc.Driver";

		try {
			Class.forName(driver);
			con = DriverManager.getConnection(url + db, "root", "");
		} catch (Exception e) {
			e.printStackTrace();
		}
		String indexDir = per_entity_index;
		StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_34);
		FSDirectory dir = FSDirectory.open(new File(indexDir));

		IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_34,
				analyzer);
		IndexWriter writer = new IndexWriter(dir, config);

		indexDocs(writer, con);
		writer.close();
	}

	static void indexDocs(IndexWriter writer, Connection con) throws Exception {
		String sql = "select full_id, fulltrigram from fulltrigramset";
		Statement stmt = con.createStatement();
		ResultSet rs = stmt.executeQuery(sql);
		while (rs.next()) {
			Document d = new Document();
			d.add(new Field("id", rs.getString("full_id"), Field.Store.YES,
					Field.Index.ANALYZED));
			d.add(new Field("name", rs.getString("fulltrigram"),
					Field.Store.YES, Field.Index.ANALYZED));
			writer.addDocument(d);
		}
	}

}
